import React, { Component } from 'react'
import { withRouter } from "react-router-dom"
import { con, white, returnr, bigimg } from "./params.module.css"
import { Modal, Button, Toast } from 'antd-mobile';
import axios from "axios"
import { loginer, token } from "../../../../redux/login/action"

import { Upload, message } from 'antd'
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';

// 下面是组件 
import photo from "../../photo/img.png"
import Shouji from "./compon/photo/shouji.js"
import Nickname from './compon/nickname/nickname';
import Sex from "./compon/sex/sex.js"
import Top from "../nine/compon/top"

import { connect } from "react-redux"
//  上传定义的const
const alert = Modal.alert;

function getBase64(img, callback) {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(img);
}

function beforeUpload(file) {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
        message.error('You can only upload JPG/PNG file!');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
        message.error('Image must smaller than 2MB!');
    }
    return isJpgOrPng && isLt2M;
}

class Params extends Component {
    componentDidMount() {
        console.log(this.props.user.data)
        if (this.props.user.data.username) {
            this.setState({
                nickname: this.props.user.data.username
            })
        }
    }

    state = {
        // 上传
        loading: false,
        upload: "",
        nickanme: "",
    }
    // 上传
    handleChange = info => {
        if (info.file.status === 'uploading') {
            this.setState({ loading: true });
            return;
        }
        if (info.file.status === 'done') {
            // Get this url from response in real world.
            getBase64(info.file.originFileObj, imageUrl =>
                this.setState({
                    imageUrl,
                    loading: false,
                }),
            );
        }
    };
    //   上传结束
    file = (e) => {
        let file = e.target.files[0];
        this.setState({
            upload: file
        })
    }
    // 上传图片
    upload = () => {
        console.log(this.state.upload)
        let forData = new FormData
        forData.append('headfile', this.state.upload)


        const headerJSON = {
            "Content-Type": "application/json;charset=UTF-8",
            "token": this.props.token.token,
            
        };
        axios({
            url: "/set/auther-center/updatepreson",
            method: "post",
            headers: headerJSON,
            data: forData
        }).then((res) => {
            console.log(res)
        })


    }
    // 返回上一页
    hist = () => {
        this.props.history.goBack()
    }
    // 账户注销
    returnr = () => {
        this.props.token("000000")
        this.props.loginer({})
        localStorage.clear()
        this.props.history.replace("/home")
    }
    render() {
        // 上传功能
        const { loading, imageUrl } = this.state;
        const uploadButton = (
            <div>
                {loading ? <LoadingOutlined /> : <PlusOutlined />}
                <div style={{ marginTop: 8 }}>Upload</div>
            </div>
        );
        return (
            <>
                <Top hist={this.hist} value={"个人信息"} />
                <div className={con}>
                    <ul className={white}>
                        <li>
                            <p>头像</p>
                            <div className={bigimg}>
                                <Button
                                    onClick={() =>
                                        alert('修改图片',
                                            <div>
                                                <form encType="multipart/form-data">
                                                    <input onChange={(e) => this.file(e)} type="file" name="filename" />
                                                </form>
                                            </div>
                                            , [
                                                { text: '取消', onPress: () => console.log('cancel') },
                                                { text: '提交', onPress: () => this.upload() },
                                            ])
                                    }
                                >
                                    <img src={photo} />
                                </Button>
                            </div>
                        </li>
                        <Nickname />
                        <Sex />
                    </ul>
                    <ul className={white}>
                        <Shouji />
                    </ul>
                    <Button
                        className={returnr}
                        onClick={() =>
                            alert('注销', '真的要退出吗', [
                                { text: '返回', onPress: () => console.log('cancel') },
                                {
                                    text: '确定',
                                    onPress: () =>
                                        new Promise((resolve) => {
                                            Toast.info('注销成功', 1);
                                            this.returnr()
                                            setTimeout(resolve);
                                        }),
                                },
                            ])
                        }
                    >
                        注销
                    </Button>
                    <Upload
                        name="avatar"
                        listType="picture-card"
                        className="avatar-uploader"
                        showUploadList={false}
                        action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
                        beforeUpload={beforeUpload}
                        onChange={this.handleChange}
                    >
                        {imageUrl ? <img src={imageUrl} alt="avatar" style={{ width: '100%' }} /> : uploadButton}
                    </Upload>
                </div>
            </>
        )
    }
}




// withRouter( new Params )
export default connect(
    state => ({
        token: state.token,
        user: state.user
    }),
    {
        loginer,
        token
    }
)(withRouter(Params))